package com.vincent.template.commons.validation.validators;

import com.vincent.template.commons.validation.constraints.MatchRegex;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * @Author Vincent Wang
 * @Date 2020/10/22 10:07
 */
public class MatchRegexValidator implements ConstraintValidator<MatchRegex, String> {

    private boolean required;
    private String regexp;
    private MatchRegex.Flag[] flags;

    @Override
    public void initialize(MatchRegex constraintAnnotation) {
        required = constraintAnnotation.required();
        regexp = constraintAnnotation.regexp();
        flags = constraintAnnotation.flags();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (StringUtils.isBlank(regexp) && flags.length == 0) {
            return true;
        }
        if (StringUtils.isBlank(value)) {
            return !required;
        }
        if (StringUtils.isNotBlank(regexp) && Pattern.compile(regexp).matcher(value).matches()) {
            return true;
        }
        if (flags.length > 0) {
            for (MatchRegex.Flag flag : flags) {
                if (Pattern.compile(flag.getRegexp()).matcher(value).matches()) {
                    return true;
                }
            }
        }
        return false;
    }
}
